﻿using Future.Common.Const;
using Future.IService;
using Future.Model.CacheModel;
using Future.Web.Extensions;
using Future.Web.Utility;
using Microsoft.AspNetCore.Authorization;

namespace Future.Web.Controllers
{
    /// <summary>
    /// 登录控制器
    /// </summary>
    public class LoginController : AuthorizeController
    {
        private readonly JwtInvoker _jwtInvoker;
        private readonly IUserBLL _userBLL;
        private readonly IMenuBLL _menuBLL;
        private readonly ICacheService _cacheService;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="jwtInvoker"></param>
        /// <param name="userBLL"></param>
        /// <param name="menuBLL"></param>
        /// <param name="cacheService"></param>
        public LoginController(JwtInvoker jwtInvoker
            , IUserBLL userBLL
            , IMenuBLL menuBLL
            , ICacheService cacheService)
        {
            _jwtInvoker = jwtInvoker;
            _userBLL = userBLL;
            _menuBLL = menuBLL;
            _cacheService = cacheService;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="loginDto"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public string Login(LoginDto loginDto)
        {
            UserModel user = _userBLL.GetUser(loginDto.UserName, loginDto.Password);
            List<MenuModel> menuModels = _menuBLL.GetMenusByUserId(user.Id);
            UserCacheModel userCacheModel = new()
            {
                User = user,
                PermissionCodes = menuModels.Select(x => x.PermissionCode).Distinct().ToList()
            };
            if (loginDto.UserName == SystemConst.ADMIN)
            {
                userCacheModel.PermissionCodes.Add(SystemConst.ADMINPERMISSIONCODE);
            }
            string token = _jwtInvoker.GetAccessToken(user, menuModels.ToHashSet());
            _cacheService.SetObject(loginDto.UserName, userCacheModel, 3000);
            return token;
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Logout()
        {
            string userName = HttpContext.GetUserName();
            _cacheService.Remove(userName);
            return "安全登出成功！";
        }
    }
}
